package com.dotflat.docs.service.impl;

import com.dotflat.docs.domain.Document;
import com.dotflat.docs.domain.DocumentDirectory;
import com.dotflat.docs.po.DocumentDirectoryPO;
import com.dotflat.docs.po.DocumentPO;
import com.dotflat.docs.repository.DocumentDirectoryRepository;
import com.dotflat.docs.repository.DocumentRepository;
import com.dotflat.docs.service.DocumentDirectoryService;
import com.dotflat.rest.PO.AreableObjectBasePO;
import com.dotflat.rest.service.impl.AreableObjectBaseServiceImpl;
import com.matt.commons.exception.BusinessException;
import com.matt.foundation.model.ErrorCode;
import com.matt.repository.care.HLEmergencyRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class DocumentDirectoryServiceImpl extends AreableObjectBaseServiceImpl<DocumentDirectory, DocumentDirectoryRepository> implements DocumentDirectoryService {

    @Autowired
    @Override
    public void setBaseRepository(DocumentDirectoryRepository repository){
        super.setBaseRepository(repository);
    }

    @Autowired
    private DocumentRepository documentRepository;
    @Override
    public DocumentDirectory add(String areaId, String staffId, AreableObjectBasePO param) {
        if (!(param instanceof DocumentDirectoryPO)){
            return super.add(areaId, staffId, param);
        }
        return add(areaId, staffId, param, o->{
            o.setStaffName(((DocumentDirectoryPO) param).getStaffName());
            o.setStaffHeadImg(((DocumentDirectoryPO) param).getStaffHeadImg());
        });
    }

    @Override
    public void add(DocumentDirectory documentDirectory) {
        baseRepository.save(documentDirectory);
    }

    @Override
    public void delete(String areaId, String staffId, AreableObjectBasePO param) {

        DocumentDirectoryPO po = new DocumentDirectoryPO();
        po.setId(param.getId());
        String dirId = param.getId();
        DocumentDirectory dir = baseRepository.getOne(dirId);
        if (dir.getItemCount()>0){
            throw new BusinessException(ErrorCode.UNDEFINED, "目录下存在文件");
        }
        super.delete(areaId, staffId, po);
    }

    @Override
    @Transactional
    public void delete(String areaId, String staffId, String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            DocumentDirectory dir = baseRepository.getOne(ids[i]);
            if (dir.getItemCount()>0){
                throw new BusinessException(ErrorCode.UNDEFINED, "目录下存在文件");
            }
        }
        super.delete(areaId, staffId, ids);
    }
}